package com.neusoft.his.sb.service.impl;

 

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

 
import com.neusoft.his.sb.entity.CommonResult;
import com.neusoft.his.sb.entity.Dept;
import com.neusoft.his.sb.mapper.DeptMapper;
import com.neusoft.his.sb.service.DeptService;
import com.neusoft.his.sb.util.HisInputDataExceptuion;
// service 层代码必须实现入库数据校验
@Service
@Transactional(rollbackFor = Exception.class) // 只是触发了事务回滚，但是没有处理异常对象
public class DeptServiceImpl implements DeptService {

	@Autowired
	DeptMapper deptMapper;

	public void setDeptMapper(DeptMapper deptMapper) {
		this.deptMapper = deptMapper;
	}

	@Override
	public CommonResult getById(int deptno) {
		if (deptno< 0 ) {
			throw new HisInputDataExceptuion();
		}
//		查询数据库动作
		Dept dept =  deptMapper.getById(deptno);
//		乐观返回结果
		CommonResult result =new CommonResult<Dept>(dept);
		// 考虑悲观的结果
		if (dept== null) {
			result.setCode(404);
		}
		return result;
	}

	@Override
	public CommonResult getAll() {
		List<Dept> lds =  deptMapper.getAll();
		CommonResult result =new CommonResult<List<Dept>>(lds);
		if (lds==null || lds.size() ==0) {
			result.setCode(404);
		}
		return result;
	}

	@Override
	public CommonResult addDept(Dept dept) {
		CommonResult result = null;
		if (dept.getDname().trim().length()>14) {
			throw new HisInputDataExceptuion();
		}
		int i = deptMapper.addDept(dept);
		result = new CommonResult<Integer>(i);
		return result;
	}

	@Override
	public CommonResult getByPrefixName(String prefixname) {
		CommonResult result = null;
		List<Dept> lds =  deptMapper.getByPrefixName(prefixname);
		result =new CommonResult<List<Dept>>(lds);
		if (lds==null || lds.size() ==0) {
			result.setCode(404);
		}
		return result;
	}


	public CommonResult modDept123(Dept dept) {
//		数据有效性校验
		if (dept== null || dept.getDeptno() == null || dept.getDeptno().intValue() < 0) {
			throw new HisInputDataExceptuion();
		}
		Dept dept2 =  deptMapper.getById(dept.getDeptno());
		if (dept2 ==null) {
			throw new HisInputDataExceptuion();
		}
		if (dept.getDname()!=null) {
			dept2.setDname(dept.getDname());
		}
		if (dept.getLoc() !=null) {
			dept2.setLoc(dept.getLoc());
		}
		int i = deptMapper.modDept(dept2);
		CommonResult result = new CommonResult<Integer>(i);
		if (i==0) {
			result.setCode(250);
		}
		return result;
	}

	@Override
	public CommonResult modDept(Dept dept) {
		
		if ( ( dept.getDname()== null || dept.getDname().trim().length()==0   ) && 
				(dept.getLoc() == null || dept.getLoc().trim().length()==0 ) ) {
			throw new HisInputDataExceptuion();
		}
		
		int i =  deptMapper.modDept(dept);
		CommonResult result = new CommonResult<Integer>(i);
		if (i==0) {
			result.setCode(250);
		}
		return result;
	}

}
